﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using HanGu.Entity;
using HanGu.Common;
using System.IO;

namespace Hangu.WebClient.Controllers
{
    public class VipController : VipBaseController
    {
        SelectList GetListFromDict(string groupName, bool IsSelectLabel = false)
        {
            var lst = serviceDict.GetByGroupName(groupName);
            if (IsSelectLabel)
            {
                lst.Insert(0, new Dictionary() { key = string.Empty, Value = "-----------请选择------------" });
            }
            SelectList sList = new SelectList(lst, "GenerateKey", "Value");
            return sList;
        }

        SelectList GetProvices(string proiceCode)
        {
            var provices = serviceArea.GetProvices();
            SelectList slist = new SelectList(provices, "AreaCode", "AreaName");
            if (string.IsNullOrEmpty(proiceCode))
            {
                proiceCode = provices != null && provices.Count > 0 ? provices[0].AreaCode : string.Empty;
            }
            ViewData["City"] = GetCitys(proiceCode);
            return slist;
        }

        SelectList GetCitys(string proiceCode)
        {
            var citys = serviceArea.GetCitys(proiceCode);
            SelectList slist = new SelectList(citys, "AreaCode", "AreaName");
            return slist;
        }
        SelectList GetMemberGrade()
        {
            SelectList selects = new SelectList(serviceDict.GetByGroupName("MemberGrade"), "GenerateKey", "Value");
            return selects;
        }
        /// <summary>
        /// 初始化 下拉列表
        /// </summary>
        /// <param name="proiceCode"></param>
        void GetSelectData(string proiceCode = null)
        {
            ViewData["SexList"] = GetListFromDict("sex");
            ViewData["IsMarry"] = GetListFromDict("marry");
            ViewData["Provice"] = GetProvices(proiceCode);
            ViewData["NativePlace"] = ViewData["Provice"];

            ViewData["Job"] = GetListFromDict("Job", true);
            ViewData["Trade"] = GetListFromDict("Trade", true);
            ViewData["Interest"] = GetListFromDict("Interest");
            ViewData["MemberGrade"] = GetListFromDict("MemberGrade");
            ViewData["Degree"] = GetListFromDict("Degree");
        }

        //
        // GET: /Vip/
        public ActionResult Login()
        {
            return View();
        }
        [HttpPost]
        public string Login(FormCollection collection)
        {
            string code = Request["code"];
            if (code != Session["ValidateCode"].ToString())
            {
                ajaxStr = string.Format(ajaxStr, 300, ResourceManager.ValidateFail, "Login", "", "");
            }
            else
            {
                MemberInfo model = new MemberInfo();
                //TryUpdateModel(model, collection);
                model.UserName = Request["User"];
                model.Pwd = Request["Pwd"];

                bool isLogin = serviceMemberInfo.IsLogin(model.UserName, Helper.MD5(model.Pwd));
                if (isLogin)
                {
                    model = serviceMemberInfo.GetByUser(model.UserName);
                    var roles = new List<Role>();
                    CurrentUserDTO curentUser = new CurrentUserDTO() { UserName = model.UserName, CurrentMemberInfo = model, Role = roles };
                    Session["Member"] = curentUser;
                    ajaxStr = string.Format(ajaxStr, 200, "登录成功", "Login", "", "");
                    //Response.Redirect(Url.Action("index","main"));
                }
                else
                {
                    ajaxStr = string.Format(ajaxStr, 300, ResourceManager.LoginFail, "Login", "", "");
                }
            }
            return "{" + ajaxStr + "}";
        }

        public ActionResult logout()
        {
            Session["Member"] = null;
            Session.Abandon();

            return View("~/Views/vip/Login.cshtml");

        }
        public ActionResult Register()
        {
            return View();
        }
        [HttpPost]
        public string Register(FormCollection collection)
        {
            string registerType = Request["registerType"];
            if (registerType == "1")
            {
                if (serviceMemberInfo.IsUserExits(collection["UserName"]))
                {
                    ajaxStr = string.Format(ajaxStr, 300, ResourceManager.UserExitsed, "VIPRegister", "", "");
                    return "{" + ajaxStr + "}";

                }
                if (Request.Cookies["VIPValidateCode"] == null || collection["code"].Trim() != Request.Cookies["VIPValidateCode"].Value)
                {
                    ajaxStr = string.Format(ajaxStr, 300, ResourceManager.CheckValidateCodeFail, "VIPRegister", "", "");
                    return "{" + ajaxStr + "}";
                }                
            }
            MemberInfo model = new MemberInfo();
            try
            {
                TryUpdateModel(model, collection);

                model.GUID = Helper.GetGuid;
                model.UserName.Trim();
                model.Email.Trim();
                bool tag = false;
                if (model.ID <= 0)
                {
                    model.Pwd = Helper.MD5(model.Pwd.Trim());
                    tag = serviceMemberInfo.Add(model);
                }
                else
                {
                    tag = serviceMemberInfo.Update(model);
                }
                if (tag)
                {
                    ajaxStr = string.Format(ajaxStr, 200, ResourceManager.VIPValidateCodeSuccess, "VIPRegister", "/vip/login", "");
                }
                else
                { ajaxStr = string.Format(ajaxStr, 300, ResourceManager.RegisterFail, "VIPRegister", "", ""); }

            }
            catch (Exception e)
            {
                base.ExceptionHand(e);
                ajaxStr = string.Format(ajaxStr, 300, ResourceManager.RegisterFail, "VIPRegister", "", "");
            }
            return "{" + ajaxStr + "}";
        }

        public ActionResult MyInfo()
        {
            MemberInfo model = this.CurentUser.CurrentMemberInfo ?? new MemberInfo();
            if (!model.NoEmail.HasValue) model.NoEmail = false;
            if (!model.NoSMS.HasValue) model.NoSMS = false;
            GetSelectData(model.Provice);
            if (string.IsNullOrEmpty(model.PicPath))
            {
                model.PicPath = "/Content/default.jpg";
            }
            ViewData["PicPath"] = model.PicPath;
            return View(model);
        }

        public ActionResult MyMessage()
        {
            MemberInfo model = this.CurentUser.CurrentMemberInfo ?? new MemberInfo();
            if (!model.NoEmail.HasValue) model.NoEmail = false;
            if (!model.NoSMS.HasValue) model.NoSMS = false;
            GetSelectData(model.Provice);
            if (string.IsNullOrEmpty(model.PicPath))
            {
                model.PicPath = "/Content/default.jpg";
            }
            ViewData["PicPath"] = model.PicPath;
            SearchParma.IntObj2 = CurentUser.CurrentMemberInfo.ID;
            var messages = serviceMessage.GetAll(SearchParma);
            ViewData["Messages"] = messages;
            return View(model);
        }
        public ActionResult EditInfo()
        {
            MemberInfo model = this.CurentUser.CurrentMemberInfo ?? new MemberInfo();
            if (!model.NoEmail.HasValue) model.NoEmail = false;
            if (!model.NoSMS.HasValue) model.NoSMS = false;
            GetSelectData(model.Provice);
            if (string.IsNullOrEmpty(model.PicPath))
            {
                model.PicPath = "/Content/default.jpg";
            }
            ViewData["PicPath"] = model.PicPath;

            return View(model);
        }
        [HttpPost]
        public void EditInfo(FormCollection collection)
        {
            MemberInfo model = new MemberInfo();

            try
            {
                TryUpdateModel(model, collection);
                model.Interest = Request["Interest"];
                bool tag = false;
                tag = serviceMemberInfo.Update(model);
                if (tag)
                {
                    ajaxStr = string.Format(ajaxStr, 200, ResourceManager.VIPValidateCodeSuccess, "VIPRegister", "", "");
                    TempData["message"] = ResourceManager.VIPValidateCodeSuccess;
                }
                else
                {
                    ajaxStr = string.Format(ajaxStr, 300, ResourceManager.RegisterFail, "VIPRegister", "", "");
                    TempData["message"] = ResourceManager.RegisterFail;
                }

            }
            catch (Exception e)
            {
                base.ExceptionHand(e);
                ajaxStr = string.Format(ajaxStr, 300, ResourceManager.RegisterFail, "VIPRegister", "", "");
                TempData["message"] = ResourceManager.RegisterFail;
            }
            this.CurentUser.CurrentMemberInfo = model;
            //TempData["message"] = ajaxStr;
            Response.Redirect("/Vip/EditInfo");
            //GetSelectData(model.Provice);
            //return View(model);
        }

        public ActionResult MyCharge()
        {
            MemberInfo model = this.CurentUser.CurrentMemberInfo ?? new MemberInfo();
            if (!model.NoEmail.HasValue) model.NoEmail = false;
            if (!model.NoSMS.HasValue) model.NoSMS = false;
            GetSelectData(model.Provice);
            if (string.IsNullOrEmpty(model.PicPath))
            {
                model.PicPath = "/Content/default.jpg";
            }
            ViewData["PicPath"] = model.PicPath;
            SearchParma.IntObj1 = model.ID;
            ViewData["ChangeCharge"] = serviceChangeCharge.GetAll(SearchParma);//改变积分
            ViewData["ChangeGrade"] = serviceGrade.GetAll(SearchParma);
            ViewData["ChargeProduct"] = serviceCharge.GetAll(SearchParma);//积分兑换
            return View(model);
        }

        public ActionResult EditPwd()
        {
            MemberInfo model = this.CurentUser.CurrentMemberInfo ?? new MemberInfo();
            if (!model.NoEmail.HasValue) model.NoEmail = false;
            if (!model.NoSMS.HasValue) model.NoSMS = false;
            //GetSelectData(model.Provice);
            if (string.IsNullOrEmpty(model.PicPath))
            {
                model.PicPath = "/Content/default.jpg";
            }
            ViewData["PicPath"] = model.PicPath;
            return View(model);
        }

        public ActionResult messagedetail(int id)
        {
            MemberInfo model = this.CurentUser.CurrentMemberInfo ?? new MemberInfo();
            if (!model.NoEmail.HasValue) model.NoEmail = false;
            if (!model.NoSMS.HasValue) model.NoSMS = false;
            //GetSelectData(model.Provice);
            if (string.IsNullOrEmpty(model.PicPath))
            {
                model.PicPath = "/Content/default.jpg";
            }
            ViewData["PicPath"] = model.PicPath;
            var message = serviceMessage.GetByID(id);
            ViewData["Message"] = message;
            message.State = 1;
            serviceMessage.Update(message);

            return View(model);
        }

        [HttpPost]
        public string SetMessage(FormCollection collection)
        {
            try
            {

                CurentUser.CurrentMemberInfo.NoEmail = collection["NoEmail"] == "checked";
                CurentUser.CurrentMemberInfo.NoSMS = collection["NoSMS"] == "checked";
                var model = CurentUser.CurrentMemberInfo ?? new MemberInfo();
                if (serviceMemberInfo.Update(model))
                {
                    ajaxStr = string.Format(ajaxStr, 200, ResourceManager.SaveSuccess, "VIPLogin", "", "");
                }
                else
                {
                    ajaxStr = string.Format(ajaxStr, 300, ResourceManager.SaveFail, "VIPLogin", "", "");
                }


            }
            catch (Exception e)
            {
                base.ExceptionHand(e);
                ajaxStr = string.Format(ajaxStr, 300, ResourceManager.SaveFail, "VIPLogin", "", "");
            }
            return "{" + ajaxStr + "}";
        }
        [HttpPost]
        public string EditPwd(FormCollection collection)
        {
            try
            {
                var model = CurentUser.CurrentMemberInfo ?? new MemberInfo();
                string oldpassword = collection["oldpassword"];
                string newPwd = collection["Pwd"];
                if (model.Pwd != Helper.MD5(oldpassword.Trim()))
                {
                    ajaxStr = string.Format(ajaxStr, 300, ResourceManager.OldPwdIsWrong, "VIPLogin", "", "");
                    return "{" + ajaxStr + "}";
                }
                else
                {
                    model.Pwd = Helper.MD5(newPwd.Trim());
                    if (serviceMemberInfo.Update(model))
                    {
                        ajaxStr = string.Format(ajaxStr, 200, ResourceManager.SaveSuccess, "VIPLogin", "", "");
                    }
                    else
                    {
                        ajaxStr = string.Format(ajaxStr, 300, ResourceManager.SaveFail, "VIPLogin", "", "");
                    }
                }

            }
            catch (Exception e)
            {
                base.ExceptionHand(e);
                ajaxStr = string.Format(ajaxStr, 300, ResourceManager.SaveFail, "VIPLogin", "", "");
            }
            return "{" + ajaxStr + "}";
        }

        [HttpPost]
        public string getValidateCode()
        {
            try
            {
                ValidateCode vCode = new ValidateCode();
                string code = vCode.CreateValidateCode(8);
                //Session["ValidateCode"] = code;
                string reciver = Request["reciver"];
                string registerType = Request["type"];
                if (string.IsNullOrEmpty(reciver))
                {
                    ajaxStr = string.Format(ajaxStr, 300, "手机或邮箱为空", "VIPLogin", "", "");
                    return "{" + ajaxStr + "}";

                }
                Response.Cookies["VIPValidateCode"].Value = code;
                Response.Cookies["VIPValidateCode"].Expires = DateTime.Now.AddMinutes(HelperCommon.ValidateCodeDated);
                bool isSuccess = false;
                var mailList = new List<string>();
                mailList.Add(reciver);
                string errorMsg = string.Empty;
                if (registerType == "1")
                {
                    MailMessage mail = new MailMessage();                    
                    mail.EmailTo = mailList;
                    mail.MailSubject = "获取校验码——汉古";
                    mail.MailBody = code;
                    isSuccess = mail.SendMailSMTP();
                    errorMsg = mail.ErrorMsg;
                }
                else
                {
                    SMS sms = new SMS();
                    sms.SMSTo = mailList;
                    sms.Message = code;
                    isSuccess=sms.Send();
                }
                if (isSuccess)
                {
                    ajaxStr = string.Format(ajaxStr, 200, ResourceManager.VIPValidateCodeSuccess, "VIPLogin", "", "");
                }
                else
                {
                    errorMsg = errorMsg ?? "发送手机失败!";
                    ajaxStr = string.Format(ajaxStr, 300, errorMsg, "VIPLogin", "", "");

                }
            }
            catch (Exception e)
            {
                base.ExceptionHand(e);
                ajaxStr = string.Format(ajaxStr, 300, ResourceManager.VIPValidateCodeFail, "VIPLogin", "", "");
            }
            return "{" + ajaxStr + "}";
        }
        public ActionResult UploadPic()
        {
            MemberInfo model = this.CurentUser.CurrentMemberInfo ?? new MemberInfo();
            if (!model.NoEmail.HasValue) model.NoEmail = false;
            if (!model.NoSMS.HasValue) model.NoSMS = false;
            //GetSelectData(model.Provice);
            if (string.IsNullOrEmpty(model.PicPath))
            {
                model.PicPath = "/Content/default.jpg";
            }
            ViewData["PicPath"] = model.PicPath;
            return View(model);
        }
        [HttpPost]
        public string UploadPic(FormCollection collection)
        {
            try
            {
                PhotoDTO photo = new PhotoDTO();
                TryUpdateModel<PhotoDTO>(photo, collection);
                if (!string.IsNullOrEmpty(photo.path))
                {
                    string path = Server.MapPath(photo.path);
                    string aimPath = path.Replace("Temp\\", "").Replace("_B", "_S");
                    StreamReader stream = new StreamReader(path);
                    //Photoer.CutForXY(path, aimPath, photo.x1, photo.y1, photo.width, photo.height,photo.zoom,100);
                    Photoer.ImgReduceCutOut(photo.x1, photo.y1, photo.width, photo.height, photo.zoom, path, aimPath);
                    //Photoer.CutForSquare(stream.BaseStream, aimPath, 120, 100);
                    CurentUser.CurrentMemberInfo.PicPath = photo.path.Replace("Temp/", "").Replace("_B", "_S");
                    if (serviceMemberInfo.Update(CurentUser.CurrentMemberInfo))
                    {
                        new UploadFileManage().DeleteFile(photo.path);
                        ajaxStr = string.Format(ajaxStr, 200, ResourceManager.SaveSuccess, "VIPLogin", aimPath, "");
                    }
                    else
                    {
                        ajaxStr = string.Format(ajaxStr, 300, ResourceManager.SaveFail, "VIPLogin", "", "");
                    }

                }
                else
                {
                    ajaxStr = string.Format(ajaxStr, 300, "图片地址为空", "VIPLogin", "", "");
                }
            }
            catch (Exception e)
            {
                base.ExceptionHand(e);
                ajaxStr = string.Format(ajaxStr, 300, ResourceManager.SaveFail + ":" + e.Message, "VIPLogin", "", "");
            }
            return "{" + ajaxStr + "}";
        }
        //
        // GET: /Vip/Details/5

        public ActionResult Details(int id)
        {
            return View();
        }

        //
        // GET: /Vip/Create

        public ActionResult Forgetpwd()
        {
            return View();
        }

        //
        // POST: /Vip/Create

        [HttpPost]
        public string Forgetpwd(FormCollection collection)
        {
            try
            {
                string username = Request["UserName"];
                string Email = Request["Email"];
                if (!string.IsNullOrEmpty(username) && !string.IsNullOrEmpty(Email))
                {
                    int result = serviceMemberInfo.IsResetPwd(username, Email);
                    switch (result)
                    {
                        case -1:
                            ajaxStr = string.Format(ajaxStr, 300, "重设失败,请联系管理员", "VIPLogin", "", "");
                            break;
                        case 0:
                            ajaxStr = string.Format(ajaxStr, 200, "重设成功", "VIPLogin", "", "");
                            break;
                        case 1:
                            ajaxStr = string.Format(ajaxStr, 300, "重设失败,用户名与邮箱不匹配", "VIPLogin", "", "");

                            break;
                        case 2:
                            ajaxStr = string.Format(ajaxStr, 300, "重设失败,请联系管理员", "VIPLogin", "", "");
                            break;
                        default:
                            ajaxStr = string.Format(ajaxStr, 300, "重设失败,请联系管理员", "VIPLogin", "", "");
                            break;
                    }
                }

            }
            catch
            {

            }
            return "{" + ajaxStr + "}";
        }

        //
        // GET: /Vip/Edit/5

        public ActionResult Edit(int id)
        {
            return View();
        }

        //
        // POST: /Vip/Edit/5

        [HttpPost]
        public ActionResult Edit(int id, FormCollection collection)
        {
            try
            {
                // TODO: Add update logic here

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

        //
        // GET: /Vip/Delete/5

        public ActionResult Delete(int id)
        {
            return View();
        }

        //
        // POST: /Vip/Delete/5

        [HttpPost]
        public ActionResult Delete(int id, FormCollection collection)
        {
            try
            {
                // TODO: Add delete logic here

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }
    }

    public class PhotoDTO
    {
        public string path { get; set; }
        public int x1 { get; set; }
        public int x2 { get; set; }
        public int y1 { get; set; }
        public int y2 { get; set; }
        public int width { get; set; }
        public int height { get; set; }
        public double zoom { get; set; }
    }
}
